package com.zengqingfa.shardingjdbc.demo.sharding.hint;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.hint.HintShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.hint.HintShardingValue;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 *
 * @fileName: ShardingTableHintAlgorithm
 * @author: zengqf3
 * @date: 2021-3-28 21:40
 * @description: 分表算法
 */
@Slf4j
public class ShardingHintAlgorithm implements HintShardingAlgorithm<Integer> {

    /**
     * 自定义Hint 实现算法
     * 能够保证绕过Sharding-JDBC SQL解析过程
     * @param availableTargetNames
     * @param hintShardingValue 不再从SQL 解析中获取值，而是直接通过
     *                      hintManager.addTableShardingValue("bill", 1)参数指定
     * @return
     */
    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames,
            HintShardingValue<Integer> hintShardingValue) {
        log.info("shardingValue={}", JSON.toJSONString(hintShardingValue));
        log.info("availableTargetNames={}", JSON.toJSONString(availableTargetNames));
        List<String> shardingResult = new ArrayList<>();
        for (String availableTargetName : availableTargetNames) {
            for (Integer shardingValue : hintShardingValue.getValues()) {
                if (availableTargetName.endsWith(String.valueOf(shardingValue % availableTargetNames.size() + 1))) {
                    log.info("availableTargetName={}", availableTargetName);
                    shardingResult.add(availableTargetName);
                }
            }
        }
        return shardingResult;
    }

}
